package com.ruoyi.project.system.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.project.system.domain.SMSRecord;
import com.ruoyi.project.system.domain.dto.SMSResult;
import com.ruoyi.project.system.mapper.SmQueryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import static com.ruoyi.common.core.text.Convert.toStr;
import static com.ruoyi.common.utils.http.HttpUtils.sendGet;

@Component
public class SmSMSService {         // MGZ TODO 2025/8/4:  短信通知

    public static String SMS_URL = "https://api-v4.mysubmail.com/sms/send?appid=109643&signature=a723473e64368a399df52cac7b2727ab&to=";

    public static String RESULT_URL = "https://cha.cdshutan.com/pages/";

    @Autowired
    private SmQueryMapper smQueryMapper;


    public SMSResult sendVerifyCode(String tel, String code) {
//        return new SMSResult();
        String content = "【天启数科】您的验证码" + code + "，该验证码1分钟内有效，请勿泄漏于他人！";
        String info = sendGet(SMS_URL + tel + "&content=" + content);
        return record(tel, content,info);
    }

    @Async
    public SMSResult sendReport(String tel, String path, String orderNo) {
//        return new SMSResult();
        String content = "【天启数科】尊敬的用户，您的报告已生成，该链接为您的报告链接，" + RESULT_URL + path + "?orderNo=" + orderNo + "，为保护个人隐私，切勿转发给他人。";
        String info = sendGet(SMS_URL + tel + "&content=" + content);
        return record(tel, content, info);
    }


    @Async
    public SMSResult sendTaxSuccessResult(String tel, Integer id) {
//        return new SMSResult();
        String content = "【天启数科】您的查询企业纳税数据采集已完成，点击链接：" + RESULT_URL + "qyns?id=" + id + "可查看，切勿转发给他人。";
        String info = sendGet(SMS_URL + tel + "&content=" + content);
        return record(tel, content, info);
    }

    public SMSResult record(String tel, String content, String info) {
        JSONObject jsonInfo = JSON.parseObject(info);
        smQueryMapper.insertSMSRecord(new SMSRecord(
                tel,
                content,
                toStr(jsonInfo.getString("send_id"), ""),
                toStr(jsonInfo.getString("msg"), ""),
                jsonInfo.getString("status")
        ));
        if ("success".equals(jsonInfo.getString("status"))) {
            return new SMSResult();
        }
        return new SMSResult(jsonInfo.getString("msg"));
    }

}
